package 链表题.查找链表中间节点;

import 链表题.ListNode;

/**
 * 快慢指针法
 */
public class Test {
    public static ListNode middleNode(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        return p1;
    }

    public static void main(String[] args) {
        ListNode head1 = ListNode.of(1, 2, 3, 4, 5);
        System.out.println(middleNode(head1));
        ListNode head2 = ListNode.of(1, 2, 3, 4, 5, 6);
        System.out.println(middleNode(head2));
    }
}
